const { createApp, defineAsyncComponent } = Vue;
const App = {
    data() {
        return {
            selectedModelValue: 'kouzi', // 默认选中的模型值
            selectedModel: {}, // 当前选中的完整模型对象
            modelOptions: [
            ],
            message: 'Hello Vue!',
            sessions: [{
                id: Date.now(),
                name: '默认会话',
                msgs: [],
                createdAt: new Date().toISOString()
            }],
            currentSessionId: null,
            msg: "",
            isSpeaking: false,
            newParamKey: '',
            isBackendReady: false,
            loadRetryCount: 0,
            terminalTabs: [
            ],
            activeTerminalTabId: 1,
            terminalContents: {},
            terminalConfigs: [
            ],
            isEditingTerminal: false,
            newTerminalConfig: {
                name: '新服务器',
                ip: '127.0.0.1',
                port: 2222,
                username: 'root',
                password: '123456',
                protocol: 'ssh'
            },
            isFirstResponse: false,
            ansiConverter: new AnsiUp()
        };
    },
    methods: {
        sendMsg() {
            const message = this.msg.trim();
            if (message) {
                this.currentSession.msgs.push({
                    id: Date.now(),
                    content: message,
                    type: 'user',
                    time: new Date().toLocaleTimeString()
                });
                this.$nextTick(() => {
                    const container = document.getElementById('chatContainer');
                    container.scrollTop = container.scrollHeight;
                });
                try {
                    pywebview.api.sendMsg(this.msg).then(result => {
                        console.log("Result from Python:", result);
                        this.saveSessions();
                    }).catch(error => {
                        console.error("Error calling Python function:", error);
                    });
                } catch (e) {
                    console.error("Exception in sendMsg():", e);
                }
                this.msg = "";
            }
        },
        startReponse() {
            this.currentSession.msgs.push({
                id: Date.now(),
                content: "",
                type: 'ai',
                isThinking: true,
                time: new Date().toLocaleTimeString()
            });
            this.$nextTick(() => {
                const container = document.getElementById('chatContainer');
                container.scrollTop = container.scrollHeight;
            });
        },
        updateMsg(response) {
            this.currentSession.msgs[this.msgs.length - 1].isThinking = false;
            this.currentSession.msgs[this.msgs.length - 1].content += response;
            this.$nextTick(() => {
                const container = document.getElementById('chatContainer');
                container.scrollTop = container.scrollHeight;
            });
        },
        updateModelForm(event) {
            console.log('Selected ID:', event.target.value);
            this.selectedModel = this.modelOptions.find(m => m.value === this.selectedModelValue) || {};
            window.pywebview.api.set_current_model(this.selectedModelValue)
                .then(() => console.log('Python后端模型已更新'))
                .catch(err => console.error('更新Python模型失败:', err));
        },
        addCustomParam() {
            if (this.newParamKey.trim()) {
                this.selectedModel.params = {
                    ...this.selectedModel.params,
                    [this.newParamKey.trim()]: 'default_value'
                };
                this.newParamKey = '';
            }
        },
        removeCustomParam(key, event) {
            event.preventDefault();
            event.stopPropagation();
            // 使用delete操作符删除对象属性
            delete this.selectedModel.params[key];
            // 确保Vue能检测到变化
            this.selectedModel.params = { ...this.selectedModel.params };
        },
        async checkBackendReady() {
            try {
                // 简单测试后端是否可用
                await window.pywebview.api.load_model_options();
                this.isBackendReady = true;
                return true;
            } catch (error) {
                console.log('后端未准备好，等待重试...');
                return false;
            }
        },
        async loadWithRetry() {
            const maxRetry = 5;
            const retryInterval = 1000; // 1秒
            while (this.loadRetryCount < maxRetry) {
                if (await this.checkBackendReady()) {
                    await this.loadModelOptions();
                    await this.loadSessions();
                    await this.loadTerminalConfigs();
                    await this.loadTerminalTabs(); 
                    return;
                }
                this.loadRetryCount++;
                await new Promise(resolve => setTimeout(resolve, retryInterval));
            }
            console.error('后端加载失败，使用默认配置');
            this.modelOptions = [
                {
                    value: 'gpt-4',
                    label: 'GPT-4',
                    apiKey: '',
                    endpoint: '',
                    params: {}
                }
            ];
        },
        async loadModelOptions() {
            try {
                const options = await window.pywebview.api.load_model_options();
                console.log("加载模型配置完成:", options);
                this.modelOptions = options || [];
                if (this.modelOptions.length > 0) {
                    this.selectedModelValue = this.modelOptions[0].value;
                    this.selectedModel = { ...this.modelOptions[0] };
                    window.pywebview.api.set_current_model(this.selectedModelValue)
                }
            } catch (error) {
                console.error("加载模型配置失败:", error);
                this.modelOptions = [
                    {
                        value: 'kouzi',
                        label: 'kouzi',
                        apiKey: '',
                        endpoint: '',
                        params: {}
                    }
                ];
            }
        },
        saveSettings(event) {
            event.preventDefault();
            event.stopPropagation();
            // 保存当前选中的模型配置
            const currentModel = this.modelOptions.find(m => m.value === this.selectedModelValue);
            if (currentModel) {
                currentModel.apiKey = this.selectedModel.apiKey;
                currentModel.endpoint = this.selectedModel.endpoint;
                currentModel.params = { ...this.selectedModel.params };
                // 调用Python后端保存配置
                window.pywebview.api.save_model_options(this.modelOptions)
                    .then(() => {
                        this.msgs.push({
                            id: Date.now(),
                            content: `
                                <div>
                                    <span>配置保存成功</span>
                                    <span class="system-detail">模型: ${this.selectedModel.label}</span>
                                </div>`,
                            type: 'system',
                            time: new Date().toLocaleTimeString()
                        });
                    })
                    .catch(error => {
                        this.msgs.push({
                            id: Date.now(),
                            content: `
                                <div>
                                    <span>配置保存失败</span>
                                    <span class="system-detail">错误: ${error.message}</span>
                                </div>`,
                            type: 'system-error',
                            time: new Date().toLocaleTimeString()
                        });
                    });
            }
            // this.closeSettings();
        },
        async switchSession(sessionId) {
            this.currentSessionId = sessionId;
            await this.saveSessions();
        },
        async deleteSession(sessionId) {
            const index = this.sessions.findIndex(s => s.id === sessionId);
            if (index !== -1) {
                this.sessions.splice(index, 1);
                if (this.currentSessionId === sessionId) {
                    this.currentSessionId = this.sessions[0]?.id;
                }
            }
            await this.saveSessions();
        },
        closeSettings() {
            document.getElementById('settingsDrawer').classList.add('-translate-x-full');
        },
        clearMessages() {
            this.msgs = [];
        },
        async newChatSession() {
            const newSession = {
                id: Date.now(),
                name: `会话 ${this.sessions.length + 1}`,
                msgs: [],
                createdAt: new Date().toISOString()
            };
            this.sessions.push(newSession);
            this.currentSessionId = newSession.id;
            this.msgs = [];
            await this.saveSessions();
        },
        async loadSessions() {
            try {
                const sessions = await window.pywebview.api.load_sessions();
                this.sessions = sessions || [];
                if (this.sessions.length === 0) {
                    this.sessions = [{
                        id: Date.now(),
                        name: '默认会话',
                        msgs: [],
                        createdAt: new Date().toISOString()
                    }];
                }
                this.currentSessionId = this.sessions[0].id;
            } catch (error) {
                console.error('加载会话失败:', error);
                this.sessions = [{
                    id: Date.now(),
                    name: '默认会话',
                    msgs: [],
                    createdAt: new Date().toISOString()
                }];
                this.currentSessionId = this.sessions[0].id;
            }
        },
        async saveSessions() {
            try {
                await window.pywebview.api.save_sessions(this.sessions);
            } catch (error) {
                console.error('保存会话失败:', error);
            }
        },
        async renameSession(sessionId, newName) {
            const session = this.sessions.find(s => s.id === sessionId);
            if (session) {
                session.name = newName;
                await this.saveSessions();
            }
        },
        switchTerminalTab(tabId) {
            console.log('切换到Tab:', tabId); // 调试用，打印当前切换的Tab ID
            this.activeTerminalTabId = tabId;
            this.terminalTabs.forEach(tab => {
                tab.active = tab.id === tabId;
            });
        },
        async closeTerminalTab(tabId) {
            const tabIndex = this.terminalTabs.findIndex(t => t.id === tabId);
            if (tabIndex !== -1) {
                this.terminalTabs.splice(tabIndex, 1);
                await this.saveTerminalTabs(); // 保存到后端
                if (this.activeTerminalTabId === tabId) {
                    this.activeTerminalTabId = this.terminalTabs[0]?.id || null;
                }
            }
        },
        async addTerminalTab(config) {
            const newTab = {
                id: Date.now(),
                name: config.name || `终端 ${this.terminalTabs.length + 1}`,
                active: false,
                connection: {
                    ip: config.ip,
                    port: config.port,
                    username: config.username,
                    password: config.password,
                    status: 'disconnected',
                    protocol: config.protocol
                },
                history: [],
                output: []
            };
            this.terminalTabs.push(newTab);
            await this.saveTerminalTabs(); // 保存到后端
            this.switchTerminalTab(newTab.id);
            this.connectTerminal(newTab);
        },

        connectTerminal(tab) {
            if (!tab.id || !tab.connection || !tab.connection.ip || !tab.connection.port) {
                console.error('连接参数不完整:', tab);
                tab.connection = {
                    ...tab.connection,
                    status: 'error'
                };
                return;
            }
            // 使用对象重新赋值确保响应性
            tab.connection = {
                ...tab.connection,
                status: 'connecting'
            };
            
            window.pywebview.api.connect_terminal(
              tab.id, tab.connection
            ).then((res) => {
                if (res) {
                    tab.connection = {
                        ...tab.connection,
                        status: 'connected'
                    };
                } else {
                    tab.connection = {
                        ...tab.connection,
                        status: 'disconnected'
                    };
                }
            }).catch(error => {
                console.error('终端连接失败:', error);
                tab.connection = {
                    ...tab.connection,
                    status: 'error'
                };
            });
        },

        async saveTerminalConfig(config) {
            const configCopy = JSON.parse(JSON.stringify(config));
            const existingIndex = this.terminalConfigs.findIndex(c => c.name === configCopy.name);
            
            try {
                if (existingIndex !== -1) {
                    this.terminalConfigs[existingIndex] = configCopy;
                } else {
                    this.terminalConfigs.push(configCopy);
                }
                // 调用后端API保存配置
                await window.pywebview.api.save_configs(this.terminalConfigs);
            } catch (error) {
                console.error('保存终端配置到后端失败:', error);
                throw error; // 抛出错误让调用方处理
            }
        },

        async deleteTerminalConfig(configName) {
            this.terminalConfigs = this.terminalConfigs.filter(c => c.name !== configName);
            try {
                // 调用后端API保存更新后的配置
                await window.pywebview.api.save_configs(this.terminalConfigs);
            } catch (error) {
                console.error('删除终端配置失败:', error);
                throw error; // 抛出错误让调用方处理
            }
        },

        getCurrentTerminalContent() {
            // 如果当前Tab没有内容数据，则初始化一个
            if (!this.terminalContents[this.activeTerminalTabId]) {
                this.terminalContents[this.activeTerminalTabId] = {
                    lines: [],       // 存储终端历史记录
                    currentInput: '' // 当前输入内容
                };
            }
            // 返回当前Tab的内容数据
            return this.terminalContents[this.activeTerminalTabId];
        },
        getCurrentTerminalTab() {
            if (!this.activeTerminalTabId) {
                return {
                    connection: {
                        protocol: '',
                        ip: '',
                        port: '',
                        latency: '--'
                    }
                };
            }
            return this.terminalTabs.find(tab => tab.id === this.activeTerminalTabId) || {
                connection: {
                    protocol: '',
                    ip: '',
                    port: '',
                    latency: '--'
                }
            };
        },
        async executeTerminalCommandForAi(command){
            console.log('执行终端命令:', command); // 调试用，打印当前执行的命令
            this.getCurrentTerminalContent().currentInput = command;
            this.executeTerminalCommand()
        },
        async executeTerminalCommand() {
            const content = this.getCurrentTerminalContent();
            const command = content.currentInput.trim();
            if (command) {
                // 添加到历史记录
                // content.lines.push({
                //     type: 'command',
                //     content: command,
                //     timestamp: Date.now()
                // });
                // 清空当前输入
                content.currentInput = '';
                this.isFirstResponse = true;
                try {
                    const output = await window.pywebview.api.execute_command(
                        this.activeTerminalTabId,
                        command
                    );
                } catch (error) {
                    console.error('执行命令失败:', error);
                    content.lines.push({
                        type: 'output',
                        content: `执行命令失败: ${error.message}`,
                        timestamp: Date.now()
                    });
                }finally{
                    this.focusTerminalInput(); // 执行命令后重新聚焦
                }
            }
        },
        getCurrentPrompt() {
            const tab = this.terminalTabs.find(t => t.id === this.activeTerminalTabId);
            if (tab) {
                return {
                    user: tab.connection.username || 'root',
                    path: '~' // 可以根据需要修改为当前路径
                };
            }
            return {
                user: 'root',
                path: '~'
            };
        },
        focusTerminalInput() {
            this.$nextTick(() => {
                const input = document.querySelector('#terminalOutput .terminal-input');
                if (input) {
                    input.focus();
                }
            });
        },
        updateTerminalOutput(tabId, output) {
            // console.log('更新终端输出-------------------:', tabId, output); // 调试用，打印更新的输出
            // console.log('更新终端输出:', tabId, output); // 调试用，打印更新的输出
            if (this.activeTerminalTabId === tabId) {
                const content = this.getCurrentTerminalContent();
                const htmlOutput = this.ansiConverter.ansi_to_html(output);
                if (this.isFirstResponse) {
                    const lastLine = content.lines[content.lines.length - 1];
                    lastLine.content += htmlOutput;
                    this.isFirstResponse = false; // 重置标志
                } else {
                    content.lines.push({
                        type: 'output',
                        content: htmlOutput,
                        timestamp: Date.now()
                    });
                }
                this.focusTerminalInput(); // 执行命令后重新聚焦

            }
        },
        // 加载终端配置到表单
        loadTerminalConfig(config) {
            this.newTerminalConfig = JSON.parse(JSON.stringify(config));
            this.isEditingTerminal = false;
        },
        async loadTerminalConfigs() {
            try {
                const savedConfigs = await window.pywebview.api.load_configs();
                this.terminalConfigs = savedConfigs || [];
            } catch (error) {
                console.error('从后端加载终端配置失败:', error);
                this.terminalConfigs = [];
            }
        },
        async loadTerminalTabs() {
            try {
                this.terminalTabs = await window.pywebview.api.load_terminal_tabs() || [];
            } catch (error) {
                console.error('加载终端标签失败:', error);
                this.terminalTabs = [];
            }
        },
        async saveTerminalTabs() {
            try {
                const tabsToSave = this.terminalTabs.map(tab => ({
                    ...tab,
                    connection: {
                        ...tab.connection,
                        status: 'disconnected'
                    }
                }));
                await window.pywebview.api.save_terminal_tabs(tabsToSave);
            } catch (error) {
                console.error('保存终端标签失败:', error);
            }
        },
        
    },
    computed: {
        currentSession() {
            return this.sessions.find(s => s.id === this.currentSessionId) || this.sessions[0];
        },
        msgs: {
            get() {
                return this.currentSession.msgs;
            },
            set(value) {
                this.currentSession.msgs = value;
            }
        }
    },
    mounted() {
        this.currentSessionId = this.sessions[0].id;
        // 替换原来的直接加载

        this.loadWithRetry();
        // this.loadTerminalConfigs();
        // 初始化选中第一个模型
        // if (this.modelOptions.length > 0) {
        //     this.selectedModelValue = this.modelOptions[0].value;
        //     this.selectedModel = { ...this.modelOptions[0] };
        //     window.pywebview.api.set_current_model(this.selectedModelValue)
        // }
        window.startReponse = this.startReponse;
        window.updateMsg = this.updateMsg;  // 挂载到全局
        window.updateTerminalOutput = this.updateTerminalOutput;  // 挂载到全局
        window.getCurrentTerminalTab = this.getCurrentTerminalTab;  // 挂载到全局
        window.executeTerminalCommandForAi= this.executeTerminalCommandForAi;  // 挂载到全局
        // window.okMsg = this.okMsg;  // 挂载到全局
        // window.setMsg = this.setMsg;
        // window.termSend = this.termSend;
    }
};
const app = Vue.createApp(App);
app.mount("#app");